﻿using CNative.Cloud.CPlatform.Engines;
using CNative.Cloud.CPlatform.Runtime.Server;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace CNative.Cloud.Swagger.Internal
{
   public class DefaultServiceSchemaProvider : IServiceSchemaProvider
    {
        private readonly IServiceEntryProvider _serviceEntryProvider;

        public DefaultServiceSchemaProvider( IServiceEntryProvider serviceEntryProvider)
        {
            _serviceEntryProvider = serviceEntryProvider;
        }

        public IEnumerable<string> GetSchemaFilesPath()
        {
            var result = new List<string>();
            var assemblieFiles = _serviceEntryProvider.GetALLEntries()
                        .Select(p => p.Type.Assembly.Location).Distinct();

            foreach (var assemblieFile in assemblieFiles)
            {
                //var fileSpan = assemblieFile.AsSpan();
                //var path = $"{fileSpan.Slice(0, fileSpan.LastIndexOf(".")).ToString()}.xml";
                var fileSpan = assemblieFile;
                var path = $"{fileSpan.Substring(0, fileSpan.LastIndexOf('.')).ToString()}.xml";
                if (File.Exists(path))
                    result.Add(path);
            }
            var annotationxmldir = AppConfig.SwaggerConfig.Options?.AnnotationXmlDir;
            if (!string.IsNullOrEmpty(annotationxmldir) && Directory.Exists(annotationxmldir)) 
            {
                var annotationxmls = Directory.GetFiles(annotationxmldir, "*.xml");
                if (annotationxmls.Any()) 
                {
                    foreach (var annotationxml in annotationxmls) 
                    {
                        result.Add(annotationxml);
                    }
                }
            }
            return result;
        }
    }
}
